package com.china08.yxyapi.schedule.homework;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.china08.yxyapi.entity.mg.homework.HomeworkClassForDayReport;
import com.china08.yxyapi.entity.mg.homework.HomeworkTask;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskClass;
import com.china08.yxyapi.entity.mg.homework.HomeworkTaskReport;
import com.china08.yxyapi.repository.mg.homework.HomeworkClassForDayReportRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskClassRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskReportRepository;
import com.china08.yxyapi.repository.mg.homework.HomeworkTaskRepository;
import com.china08.yxyapi.util.DateUtils;
import com.china08.yxyapi.util.YxUserPointsUtilV3;
import com.china08.yxyapi.util.YxyScheduleRunnableUtil;

@Component
public class HomeworkClassForDayReportTask {

    @Autowired
    HomeworkClassForDayReportRepository homeworkClassForDayReportRepository;

    @Autowired
    HomeworkTaskClassRepository homeworkTaskClassRepository;

    @Autowired
    HomeworkTaskReportRepository homeworkTaskReportRepository;

    @Autowired
    HomeworkTaskRepository homeworkTaskRepository;

    @Autowired
    YxUserPointsUtilV3 yxUserPointsUtilV3;

    private static final Logger log = LoggerFactory.getLogger(HomeworkClassForDayReportTask.class);

    // CRON表达式 含义
    // "0 0 12 * * ?" 每天中午十二点触发
    // "0 15 10 ? * *" 每天早上10：15触发
    // "0 15 10 * * ?" 每天早上10：15触发
    // "0 15 10 * * ? *" 每天早上10：15触发
    // "0 15 10 * * ? 2005" 2005年的每天早上10：15触发
    // "0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发
    // "0 0/5 14 * * ?" 每天从下午2点开始到2：55分结束每5分钟一次触发
    // "0 0/5 14,18 * * ?" 每天的下午2点至2：55和6点至6点55分两个时间段内每5分钟一次触发
    // "0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发
    // "0 10,44 14 ? 3 WED" 三月的每周三的14：10和14：44触发
    // "0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10：15触发
    /** 每天一点触发，统计前一天数据 **/
    @Scheduled(cron = "0 0 1 * * ?")
    // @Scheduled(fixedRate = 1000 * 60 * 10)
    public void executeFileDownLoadTask() {
    	
        // ##
        // 检测定时任务是否可执行
        if (!YxyScheduleRunnableUtil.checkRunnable()) { return; }
    	
        log.info("定时任务开始...");
        // 昨天时间
        Date date = DateUtils.subtractDay(new Date(), 1);
        // 0-点时间
        Date beginDate = DateUtils.getFirstDay(date);
        // 24-点时间
        Date endDate = DateUtils.getTimesnight(date);
        // 获取班级有截止的作业
        List<HomeworkTaskClass> HomeworkTaskClassz = homeworkTaskClassRepository
                .findByPredictDateBetweenEqual(beginDate, endDate);
        if (HomeworkTaskClassz != null && HomeworkTaskClassz.size() > 0) {
            for (HomeworkTaskClass homeworkTaskClass : HomeworkTaskClassz) {
                try {
                    HomeworkClassForDayReport homeworkClassForDayReport = new HomeworkClassForDayReport();
                    homeworkClassForDayReport.setId(UUID.randomUUID().toString());
                    homeworkClassForDayReport.setClassId(homeworkTaskClass.getClassId());
                    homeworkClassForDayReport.setClassNick(homeworkTaskClass.getClassName());
                    homeworkClassForDayReport.setSchoolId(homeworkTaskClass.getSchoolId());
                    homeworkClassForDayReport.setStage(homeworkTaskClass.getStage());
                    homeworkClassForDayReport.setStatisDate(date);
                    homeworkClassForDayReport.setSubject(homeworkTaskClass.getSubject());
                    homeworkClassForDayReport.setSubjectName(homeworkTaskClass.getSubjectName());
                    homeworkClassForDayReport.setCompletionRate(this.getDouble1(homeworkTaskClass.getSubmitOfStudent(),
                            homeworkTaskClass.getNumOfStudent())); // 完成率
                    homeworkClassForDayReport.setExcellentRate(0D); // 优秀率
                    // 优秀率处理
                    List<Integer> statusOfFinishedLst = new ArrayList<Integer>();
                    statusOfFinishedLst.add(1); // 已完成
                    statusOfFinishedLst.add(2); // 已批阅
                    List<HomeworkTaskReport> homeworkTaskReports = homeworkTaskReportRepository
                            .findByTaskIdAndClassIdAndStatusOfFinishedInOrderByRightRateDesc(
                                    homeworkTaskClass.getTaskId(), homeworkTaskClass.getClassId(), statusOfFinishedLst);
                    if (homeworkTaskReports != null && homeworkTaskReports.size() > 0) {
                        int count = 0;
                        // double rightRate = 0d;
                        double scoreRate = 0d;
                        for (HomeworkTaskReport homeworkTaskReport : homeworkTaskReports) {
                            count++;
                            // rightRate = rightRate + homeworkTaskReport.getRightRate();
                            scoreRate = scoreRate + homeworkTaskReport.getScoreRate();
                        }
                        // homeworkClassForDayReport.setExcellentRate(getDouble2(rightRate, count)); // 优秀率
                        homeworkClassForDayReport.setScoreRate(getDouble2(scoreRate, count)); // 得分率
                    }
                    homeworkClassForDayReportRepository.save(homeworkClassForDayReport);
                } catch (Exception e) {
                    log.info("任务异常...");
                }
            }

            // ##
            // 统计积分
            for (HomeworkTaskClass homeworkTaskClass : HomeworkTaskClassz) {
                HomeworkTask homeworkTask = homeworkTaskRepository.findOne(homeworkTaskClass.getTaskId());
                if (homeworkTask != null) {
                    Double double1 = homeworkTaskClass.getSubmitOfStudent().doubleValue()
                            / homeworkTaskClass.getNumOfStudent();
                    try {
                        Thread thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    if (double1 >= 0.5) {
                                        if (double1 > 0.8) {
                                            yxUserPointsUtilV3.finishHomeworkMore(homeworkTask.getPublishUserId());
                                        } else {
                                            yxUserPointsUtilV3.finishHomeworkOther(homeworkTask.getPublishUserId());
                                        }
                                    } else {
                                    	yxUserPointsUtilV3.finishHomework50(homeworkTask.getPublishUserId());
                                    }
                                } catch (Exception e) {
                                }
                            }
                        });
                        thread.run();
                    } catch (Exception e) {
                    }
                }
            }
        }
        log.info("定时任务结束...");
    }

    /** 百分比转化 **/
    private Double getDouble1(Integer x1, Integer sum) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.####");
        if (x1 == null || sum == null) {//
            return 0d;
        } else if (x1 <= 0 || sum <= 0) {//
            return 0d;
        } else {
            double d = (x1 * 0.1) / (sum * 0.1);
            return Double.parseDouble(df.format(d)) * 100;
        }
    }

    /** 百分比转化 **/
    private Double getDouble2(double x1, int sum) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");
        if (x1 <= 0 || sum <= 0) {//
            return 0d;
        } else {
            double d = (x1 * 0.1) / (sum * 0.1);
            return Double.parseDouble(df.format(d));
        }
    }
}
